<?php
use yii\bootstrap\ActiveForm;
?>
<link rel="stylesheet" href="../static/dist/css/AdminLTE.min.css" type="text/css">
<link rel="stylesheet" href="../static/bootstrap/css/bootstrap.min.css" type="text/css">
<link rel="stylesheet" href="../static/plugins/datatables/jquery.dataTables.css" type="text/css">
<link rel="stylesheet" href="../static/css/admin.css" type="text/css">
<link rel="stylesheet" href="../static/jBox/Skins/Metro/jbox.css" type="text/css">
<link rel="stylesheet" href="../static/plugins/datepicker/datepicker3.css" type="text/css">

<style>
    .dataTables_length {
        margin-top: 10px;
    }
    .dataTable>tbody>tr>td {
        vertical-align: middle;
        font-size: 0.8em;
        padding: 8px 18px;
    }
    .dataTable>thead>tr>th {
        vertical-align: middle;
        font-size: 0.8em;
    }
    .source_type_class {
        min-height: 20px;
        padding-left: 20px;
        margin-bottom: 0;
        font-weight: 400;
        cursor: pointer;
    }
    .form-left{
        border-right: 1px solid #dddddd;
    }
    .examine-content{
        width: 1000px;
        margin-left:-300px;
    }
    .examine-content .input-group .form-control{
        margin-bottom: 20px;
        height: 30px ;
        line-height: 30px;
    }
    .examine-content button{
        margin: 10px;
    }
    .tabCenter td{text-align: center; font-size: 14px}
    .tabCenter th{text-align: center}
</style>
<div class="tabs-panel">
    <div class="row">
        <div class="col-xs-12">
            <div class="box">
                <div class="box-header">
                    订单编号：
                    <input class="depart-input" id="searchCode" style="width: 160px" type="text">&nbsp;&nbsp;
                    状态：
                    <select id="status" class="depart-input" style="width: 120px">
                        <option value="">全部</option>
                        <option value="0">创建</option>
                        <option value="1">审核</option>
                        <option value="9">作废</option>
                    </select>&nbsp;
                    <button type="button" class="btn btn-primary depart-modal" id="select_button" style="width: 80px;">查询</button>&nbsp;
                    <button type="button" class="btn btn-warning depart-modal" id="reset_button" style="width: 80px;">重置</button>
                </div>
                <div class="box-body">
                    <table id="table_id_example" class="display">
                        <thead>
                        <tr>
                            <th style="width: 20%">操作</th>
                            <th style="width: 20%">订单编号</th>
                            <th style="width: 20%">收货人</th>
                            <th style="width: 20%">收货时间</th>
                            <th style="width: 20%">状态</th>
                        </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade modalBox" id="show-dtl" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog" style="width:85%">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                    &times;
                </button>
                <h4 class="modal-title" id="myModalLabel">
                    异常单详情
                </h4>
            </div>
            <div class="modal-body">
                <div class="box-body">
                    <div class="col-md-12">
                        <div class="form-group col-md-6">
                            <label for="exampleInputPassword1">订单编号</label>
                            <input type="text" style="width: 50%;" id="billNo" class="form-control" disabled>
                        </div>
                        <div class="form-group col-md-6">
                            <label for="exampleInputEmail1">状态</label>
                            <input type="text" style="width: 50%;" id="diffStatus" class="form-control" disabled>
                        </div>
                    </div>
                    <div class="col-md-12">
                        <div class="form-group col-md-6">
                            <label for="exampleInputPassword1">收货人</label>
                            <input type="text" style="width: 50%;" id="creator" class="form-control" disabled>
                        </div>
                        <div class="form-group col-md-6">
                            <label for="exampleInputEmail1">收货时间</label>
                            <input type="text" style="width: 50%;" id="createTime" class="form-control" disabled>
                        </div>
                    </div>
                    <div class="col-md-12">
                        <div class="form-group col-md-6">
                            <label for="exampleInputPassword1">备注</label>
                            <textarea class="form-control xheditor" id="remark" style="width: 100%;"></textarea>
                        </div>
                    </div>
                    <br>
                    <table id="table_dtl_list" class="table table-bordered table-hover tabCenter">
                        <thead>
                        <tr>
                            <th style="width: 10%">物料编码</th>
                            <th style="width: 10%">物料名称</th>
                            <th style="width: 10%">所属仓库</th>
                            <th style="width: 12%">供应商</th>
                            <th style="width: 10%">订货数量</th>
                            <th style="width: 10%">发货数量</th>
                            <th style="width: 10%">收货数量</th>
                            <th style="width: 10%">差异</th>
                            <th style="width: 10%">图片</th>
                            <th style="width: 10%">备注</th>
                            <th style="width: 10%">操作</th>
                        </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>

                </div>
                <!-- /.box-body -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <a type="button" href="javascript:auditDiff()" id="show-dtl-btn" class="btn btn-primary">提交</a>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal -->
</div>


<div class="modal fade modalBox" id="show-check" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog" style="width:75%">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                    &times;
                </button>
                <h4 class="modal-title" id="myModalLabel">
                    发货明细
                </h4>
            </div>
            <div class="modal-body">
                <div class="box-body">
                    差异数量：<span id="spanQty" style="color: red"></span>
                    <table id="table_check_list" class="table table-bordered table-hover tabCenter">
                        <thead>
                        <tr>
                            <th style="width: 12%">物料编码</th>
                            <th style="width: 12%">物料名称</th>
                            <th style="width: 12%">批次</th>
                            <th style="width: 10%">单价</th>
                            <th style="width: 10%">发货数量</th>
                            <th style="width: 10%">仓库异常</th>
                            <th style="width: 10%">门店异常</th>
                            <th style="width: 20%">备注</th>
                        </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                    *注：若没有异常问题，以上数量不需要填写并请备注原因。
                </div>
                <!-- /.box-body -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <a type="button" href="javascript:doCheck()" id="show-check-btn" class="btn btn-primary">提交</a>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal -->
</div>


<!-- 查看图片 -->
<div class="modal fade" id="show-img-modal" style="background: rgba(236, 230, 230, 0.3);" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog" style="width: 50%;">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title" id="myModalLabel">查看图片</h4>
            </div>
            <div class="modal-body">
                <div class="box-body" id="dtlImgBox" style="text-align: center">

                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>


<!-- 固定js -->
<script type="text/javascript" src="../static/plugins/jQuery/jquery-2.2.3.min.js"></script>
<script type="text/javascript" src="../static/bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript" src="../static/plugins/datatables/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="../static/plugins/datatables/dataTables.bootstrap.min.js"></script>
<script type="text/javascript" src="../static/jBox/jquery.jBox-2.3.min.js"></script>
<script type="text/javascript" src="../static/jBox/i18n/jquery.jBox-zh-CN.js"></script>
<!-- 自定义js -->
<script type="text/javascript" src="/static/plugins/datepicker/bootstrap-datepicker.js"></script>
<script type="text/javascript" src="/static/plugins/datepicker/locales/bootstrap-datepicker.zh-CN.js"></script>
<script type="text/javascript" src="/static/app/global.js?version=<?=Yii::$app->params['version']?>"></script>
<script>
    var table = null;
    var batchData = {};
    $(function () {
        table = $('#table_id_example').DataTable({
            dom: '<"top">rt<"bottom"flip><"clear">',
            language: {
                "sUrl": '../static/plugins/datatables/language.json'
            },
            "searching": false,
            "processing": true,
            "serverSide": true,
            "scrollY": "550px",
            "scrollCollapse": true,
            "scrollX": true,
            //"aLengthMenu": [1, 3, 5],
            ajax: {
                url: '/bill-diff/get-list',
                type: 'post',
                data: function (d) {
                    d.searchCode = $('#searchCode').val();
                    d.status = $('#status').val();
                },
                error: getError
            },
            aoColumns: [
                {"data": "", "bSortable": false},
                {"data": "billNo", "bSortable": true},
                {"data": "creator", "bSortable": false},
                {"data": "createTime", "bSortable": false},
                {"data": "diffStatus", "bSortable": false},
            ],
            columnDefs: [
                {
                    "targets": [0],
                    "orderable": false,
                    "searchable": false,
                    "render": function (data, type, full) {
                        var html = '';
                        if (full.diffStatus == 0) {
                            html += '<a href="javascript:showDtl(' + full.billNo + ')">审核</a>';
                        }
                        return html;
                    }
                },
                {
                    "targets": [1],
                    "orderable": false,
                    "searchable": false,
                    "render": function (data, type, full) {
                        var html = '';
                        html += '<a href="javascript:showDtl(' + full.billNo + ')">' + data + '</a>';
                        return html;
                    }
                },
                {
                    "targets": [-1],
                    "orderable": false,
                    "searchable": false,
                    "render": function (data, type, full) {
                        if (data == '0') return '创建';
                        if (data == '1') return '已审核';
                        if (data == '9') return '作废';
                    }
                }
            ],
            order: [[1, "desc"]]
        });

        $("#select_button").on('click', function () {
            table.ajax.reload();
        });

        $("#reset_button").on('click', function () {
            $('#searchCode').val('');
            $('#status').val('');
            table.ajax.reload();
        });

        $('#billDate').datepicker({language:'zh-CN', format:'yyyy-mm-dd'});

        $(document).on('blur', 'input[name=whQty],input[name=shQty]', function () {
            countQty();
        });
    });

    function countQty() {
        var diffQty = batchData[currCode]['diffQty'];
        $.each($('input[name=whQty],input[name=shQty]'), function () {

            var val = $(this).val();
            var isInt = /^\d+$/;
            if (val == '' || !isInt.test(val)) {
                return;
            }

            diffQty = parseInt(diffQty) - parseInt(val);
        });
        $('#spanQty').html(diffQty.toString());
    }

    //查看详情
    function showDtl(billNo) {
        batchData = {};
        $.post('/bill-diff/get-dtl', {billNo: billNo},
            function (o) {
                if (o.code != 200) {
                    $.jBox.tip(o.val, '错误');
                    return;
                }

                $('#billNo').val(o.data['billNo']);
                $('#diffStatus').val(o.data['statusName']);
                $('#creator').val(o.data['creator']);
                $('#createTime').val(o.data['createTime']);
                $('#remark').val(o.data['remark']);

                var html = '';
                $.each(o.data['dtl'], function (i, v) {
                    var diffQty = parseInt(v['deliverQty']) - parseInt(v['receiptQty']);
                    html += '<tr>';
                    html += '<td>' + v['materielCode'] + '</td>';
                    html += '<td>' + v['materielName'] + '</td>';
                    html += '<td>' + v['warehouseName'] + '</td>';
                    html += '<td>' + v['supplierName'] + '</td>';
                    html += '<td>' + v['qty'] + '</td>';
                    html += '<td>' + v['deliverQty'] + '</td>';
                    html += '<td>' + v['receiptQty'] + '</td>';
                    html += '<td>' + diffQty + '</td>';
                    html += '<td><a name="show-img" onclick="shopImg(\''+billNo+'\','+v['materielId']+')">【查看】</a></td>';
                    html += '<td>' + v['remark'] + '</td>';
                    html += '<td><a href="javascript:checkDiff(\'' + v['materielId'] + '\')">核对</a></td>';
                    html += '</tr>';
                    batchData[v['materielId']] = {'materielName': v['materielName'], 'diffQty': diffQty, 'batch': {}};
                });

                if (o.data['diffStatus'] == '0') {
                    $('#show-dtl-btn').show();
                    $('#show-check-btn').show();
                } else {
                    $('#show-dtl-btn').hide();
                    $('#show-check-btn').hide();
                }
                $('#table_dtl_list tbody').html(html);
            },
            'json'
        );

        $('#show-dtl').modal('show');
    }

    //查看发货批次数据
    var currCode = '';
    function checkDiff(code) {
        currCode = code;
        var billNo = $('#billNo').val(),
            diffQty = batchData[currCode]['diffQty'];
        $.post('/bill-diff/check-diff', {billNo: billNo, materielId: code},
            function (o) {
                if (o.code != 200) {
                    $.jBox.tip('数据异常', '错误');
                    return;
                }

                var html = '';
                $.each(o.data, function (i, v) {
                    var whQty = v['whQty'] || 0,
                        shQty = v['shQty'] || 0,
                        remark = v['remark'] || '',
                        temp = batchData[currCode]['batch'][v['batch']] ? batchData[currCode]['batch'][v['batch']] : null;

                    if (temp) whQty = temp['whQty'] || 0;
                    if (temp) shQty = temp['shQty'] || 0;
                    if (temp) remark = temp['remark'] || '';

                    html += '<tr name="tr_batch">';
                    html += '<td>' + v['materielCode'] + '</td>';
                    html += '<td>' + v['materielName'] + '</td>';
                    html += '<td>' + v['batch'] + '</td>';
                    html += '<td>' + v['price'] + '</td>';
                    html += '<td>' + v['deliverQty'] + '</td>';
                    html += '<td><input type="text" name="whQty" value="' + whQty + '" style="width: 70px"/></td>';
                    html += '<td><input type="text" name="shQty" value="' + shQty + '" style="width: 70px"/></td>';
                    html += '<td><input type="text" name="remark" value="' + remark + '" style="width: 95%"/></td>';
                    html += '</tr>';
                });
                $('#table_check_list tbody').html(html);
                countQty();
            },
            'json'
        );
        $('#spanQty').html(diffQty);
        $('#show-check').modal('show');
    }

    //保存批次数据
    function doCheck() {
        var tempData = $('tr[name=tr_batch]');

        var batchCnt = 0,
            msg = '',
            diffQty = batchData[currCode]['diffQty'];

        $.each(tempData, function () {
            var batch = $(this).find('td').eq(2).html(),
                whQty = $(this).find('input[name=whQty]').val() || 0,
                shQty = $(this).find('input[name=shQty]').val() || 0,
                remark = $(this).find('input[name=remark]').val();

            var isInt = /^\d+$/;
            if (whQty != '' && !isInt.test(whQty)) {
                msg = '请输入正确的仓库异常数量';
                return false;
            }
            if (shQty != '' && !isInt.test(shQty)) {
                msg = '请输入正确的门店异常数量';
                return false;
            }
            batchData[currCode]['batch'][batch] = {
                'batch': batch,
                'whQty': parseInt(whQty),
                'shQty': parseInt(shQty),
                'remark': remark
            };
            batchCnt += parseInt(whQty) + parseInt(shQty);
        });

        if (msg) {
            $.jBox.tip(msg, '错误');
            return;
        }

        if (diffQty != batchCnt) {
            $.jBox.tip('差异数量不匹配，请检查', '错误');
            return;
        }
        $('#show-check').modal('hide');
    }

    //审核异常
    function auditDiff() {
        if (!batchData) {
            $.jBox.tip('请检查数据', '错误');
            return;
        }

        var ckName = '', ckFlg = 0;
        $.each(batchData, function (i1, v1) {
            var batchCnt = 0,
                diffQty = v1['diffQty'];
            if(!v1['batch']) {
                ckFlg = 1;
                return false;
            }
            $.each(v1['batch'], function (i2, v2) {
                batchCnt += v2['whQty'];
                batchCnt += v2['shQty'];
            });

            if(diffQty != batchCnt) {
                ckName = v1['materielName'];
                return false;
            }
        });
        if(ckName) {
            $.jBox.tip('【'+ ckName +'】差异数量不匹配，请检查', '错误');
            return;
        }

        var tip = ckFlg ? '有物料未核对异常数量' : '提交后将改变实时库存数量';
        $.jBox.confirm(tip, "是否继续？", function (v) {
            if (v == 'ok') {
                var billNo = $('#billNo').val();
                $.post('/bill-diff/audit-diff', {billNo: billNo, batchData: batchData, remark: $('#remark').val() },
                    function (o) {
                        if (o.code == 200) {
                            $.jBox.tip(o.val, 'success');
                            $('#show-dtl').modal('hide');
                            table.draw(false);
                            return;
                        }
                        $.jBox.tip(o.val, '错误');
                    },
                    'json'
                );
            } else {
                $.jBox.close();
            }
        });

    }

    //修改订单状态
    function editStatus(billNo) {

        $.jBox.confirm("请确认操作", "提示", function(v){
            if (v == 'ok'){
                $.post('/bill-diff/chanage-status', {billNo:billNo},
                    function (data) {
                        if(data.code == 200){
                            $.jBox.tip('操作成功', 'success');
                            table.draw(false);
                        }else{
                            $.jBox.error(data.val, '错误');
                        }
                    },
                    'json'
                );
            }else{
                $.jBox.close();
            }
        });

    }

    //查看图片
    function shopImg(billNo,materielId) {

        $('#dtlImgBox').empty();
        $.post('/bill/get-bill-img', {billNo: billNo, materielId: materielId},
            function (o) {
                if (o.code == 200) {
                    if(o.data){
                        $.each(o.data['img'], function (i, v) {
                            $('#dtlImgBox').append('<img src="'+v+'" style="width: 500px; margin: 5px">');
                        })
                    }
                    $('#show-img-modal').modal('show');
                } else {
                    $.jBox.error(o.val, '错误');
                }
            },
            'json'
        );
    }
</script>